function DragImgUpload(id,options) {
    this.me = $(id);
    var defaultOpt = {
        boxWidth:'150px',
        boxHeight:'150px'
    }
    this.preview = $('<div id="preview"><img src="../../uploader/img/upload.png" class="img-responsive"  style="width: 100%;height: 128px;" alt="" title=""> </div>');
    this.opts=$.extend(true, defaultOpt,{
    }, options);
    this.init();
    this.callback = this.opts.callback;
}
 function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}
function photoCompress(file,w,objDiv,filename){

    var ready=new FileReader();
    /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
    ready.readAsDataURL(file);

    ready.onload=function(){
        var re=this.result;
        canvasDataURL(re,w,objDiv,filename)
    }
}
function canvasDataURL(path, obj, callback,filename){
    var img = new Image();
    img.src = path;
    img.onload = function(){
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            scale = w / h;
        w = obj.width || w;
        h = obj.height || (w / scale);
        var quality = 0.7;  // 默认图片质量为0.7
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量
        if(obj.quality && obj.quality <= 1 && obj.quality > 0){
            quality = obj.quality;
        }
        // quality值越小，所绘制出的图像越模糊
        var base64 = canvas.toDataURL('image/jpeg', quality);
        // 回调函数返回base64的值
        var  tt= dataURLtoFile(base64,filename);
        callback(tt);
    }
}

function compress  (files, fn, ios){
    // 对不支持canvas上的toBlob方法的浏览器兼容处理
    if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
            value: function (callback, type, quality) {
                var dataURL = this.toDataURL(type, quality).split(",")[1];
                setTimeout(function () {
                    var binStr = atob(dataURL);
                    var len = binStr.length;
                    var arr = new Uint8Array(len);

                    for (var i = 0; i < len; i++) {
                        arr[i] = binStr.charCodeAt(i);
                    }

                    callback(new Blob([arr], { type: type || "image/png" }));
                });
            }
        });
    }
    var file = files;
    if (ios === true) {
        function dataURLtoFile(dataurl) {
            var arr = dataurl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        }
        file = dataURLtoFile(file);
    }
    var Orientation = null;
    var img = new Image();
    // 创建读取文件对象
    var render = new FileReader();

    // 找到canvas,准备画图
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    if (file.type.indexOf("image") !== -1) {
        // 读取file文件,得到的结果为base64位
        render.readAsDataURL(file);
    }
    // 要对图片旋转，需要获取当前图片的信息，需要引入exif插件，可以直接在入口index.html用CDN引入
    //  <script src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.js"></script>

    // 获取图片信息
    EXIF.getData(file, function () {
        Orientation = EXIF.getTag(this, "Orientation");
    });
    render.onload = function (result) {
        // 把读取到的base64图片设置给img的src属性
        var src = render.result;
        img.src = src;
    };

    img.onload = function () {
        // 加载完毕后获取图片的原始尺寸
        var origin_width = this.width;
        var origin_height = this.height;
        // 设置最大允许宽高,根据需求自己设置,值越大,图片大小越大
        var max_width = 400;
        var max_height = 400;

        // 最终宽高
        var imgWidth = origin_width;
        var imgHeight = origin_height;
        if (origin_width > max_width || origin_height > max_height) {
            if (origin_width / origin_height > max_width / max_height) {
                imgWidth = max_width;
                imgHeight = Math.round(max_width * (origin_height / origin_width));
            } else {
                imgHeight = max_height;
                imgWidth = Math.round(max_height * (origin_width / origin_height));
            }
        }
        canvas.width = imgWidth;
        canvas.height = imgHeight;
        if (Orientation && Orientation != 1) {
            switch (Orientation) {
                case 6: // 旋转90度
                    canvas.width = imgHeight;
                    canvas.height = imgWidth;
                    context.rotate(Math.PI / 2);
                    // (0,-imgHeight) 从旋转原理图那里获得的起始点
                    context.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
                    break;
                case 3: // 旋转180度
                    context.rotate(Math.PI);
                    context.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
                    break;
                case 8: // 旋转-90度
                    canvas.width = imgHeight;
                    canvas.height = imgWidth;
                    context.rotate((3 * Math.PI) / 2);
                    context.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                    break;
            }
        } else {
            context.drawImage(this, 0, 0, imgWidth, imgHeight);
        }

        // 此处toBlob方法在iOS上有兼容问题，已做处理
        // toBlob第一个参数是回调函数，第二个参数是要转换的格式，第三个是转换的图片的质量0~1
        canvas.toBlob(function (result) {
            // 用回调函数将处理的结果返回出去
            fn(result);
        }, "image/jpg", 0.9);
    };
}
//定义原型方法
DragImgUpload.prototype = {
    init:function () {
        this.me.append(this.preview);
        this.me.append(this.fileupload);
        this.cssInit();
        this.eventClickInit();
    },
    cssInit:function () {
        this.me.css({
            'width':this.opts.boxWidth,
            'height':this.opts.boxHeight,
            'border':'1px solid #cccccc',
            'padding':'10px',
            'cursor':'pointer'
        })
        this.preview.css({
            'height':'100%',
            'overflow':'hidden'
        })

    },
    onDragover:function (e) {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    },
    onDrop:function (e) {
        var self = this;
        e.stopPropagation();
        e.preventDefault();
        var fileList = e.dataTransfer.files; //获取文件对象
        // do something upload
        if(fileList.length == 0){
            return false;
        }
        //检测文件是不是图片
        if(fileList[0].type.indexOf('image') === -1){
            alert("您拖的不是图片！");
            return false;
        }

        //拖拉图片到浏览器，可以实现预览功能
        var img = window.URL.createObjectURL(fileList[0]);
        var filename = fileList[0].name; //图片名称
        var filesize = Math.floor((fileList[0].size)/1024);
        if(filesize>50000){
            alert("上传大小不能超过50000K.");
            return false;
        }
        self.me.find("img").attr("src",img);
        self.me.find("img").attr("title",filename);
        if(this.callback){
            this.callback(fileList);
        }
    },
    eventClickInit:function () {
        var self = this;
        this.me.unbind().click(function () {
            self.createImageUploadDialog();
        })
        var dp = this.me[0];
        dp.addEventListener('dragover', function(e) {
            self.onDragover(e);
        });
        dp.addEventListener("drop", function(e) {
            self.onDrop(e);
        });


    },

    onChangeUploadFile:function () {
        var back=this.callback;
        var fileInput = this.fileInput;
        var files = fileInput.files;
        var file = files[0];
        var img = window.URL.createObjectURL(file);
        var filename = file.name;
        var filesize = Math.floor((file.size)/1024);
        this.me.find("img").attr("src",img);
        this.me.find("img").attr("title",filename);
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if(isiOS){
            lrz(file)
                .then(function (rst) {
                    console.log(rst)
                    var  tt= dataURLtoFile(rst.base64,filename);
                    if(back){
                        console.log(tt);
                        back(tt);
                    }
                })
                .catch(function (err) {　 mui.toast(err);　　　})
                .always(function (rst) {
                });
        }
        else {
            //检测文件是不是图片
            if (filesize > 1025) {
                photoCompress(file, {
                    quality: 0.5
                }, back,filename)
                }
            else {
                back(file);
            }

        }
    },
    createImageUploadDialog:function () {
        var fileInput = this.fileInput;

        function getIos() {
            if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                return true;
            } else {
                return false;
            }
        }
        if (!fileInput) {
            //创建临时input元素
            fileInput = document.createElement('input');
            //设置input type为文件类型
            fileInput.type = 'file';
            // fileInput.capture='camera';
            if (getIos()) {
                fileInput.removeAttribute("capture");
            }
            //设置文件name
            fileInput.name = 'ime-images';
            fileInput.accept='image/*';
            //允许上传多个文件
            fileInput.multiple = true;
            fileInput.onchange  = this.onChangeUploadFile.bind(this);
            this.fileInput = fileInput;
        }
        //触发点击input点击事件，弹出选择文件对话框
        fileInput.click();
    }

}